{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>创建模板 - 模板管理系统</title>
    <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
    <link href="{% static 'css/bootstrap-icons.css' %}" rel="stylesheet">
    <style>
        /* 步骤指示器样式 */
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2rem;
            position: relative;
        }
        .step {
            flex: 1;
            text-align: center;
            position: relative;
            transition: all 0.3s ease;
        }
        .step:not(:last-child)::after {
            content: '';
            position: absolute;
            top: 15px;
            right: -50%;
            width: 100%;
            height: 2px;
            background: #dee2e6;
            z-index: -1;
            transition: background 0.5s ease;
        }
        .step.active::after, .step.completed::after {
            background: linear-gradient(90deg, #007bff, #0056b3);
        }
        .step-circle {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            background: #dee2e6;
            color: #6c757d;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 0.5rem;
            font-weight: bold;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .step.active .step-circle {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
            transform: scale(1.1);
            box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
        }
        .step.completed .step-circle {
            background: linear-gradient(135deg, #28a745, #1e7e34);
            color: white;
            transform: scale(1.05);
            box-shadow: 0 3px 8px rgba(40, 167, 69, 0.3);
        }
        .step-label {
            font-size: 0.875rem;
            font-weight: 500;
            transition: color 0.3s ease;
        }
        .step.active .step-label {
            color: #007bff;
            font-weight: 600;
        }
        .step.completed .step-label {
            color: #28a745;
        }
        
        /* 内容区域动画 */
        .step-content {
            animation: fadeInUp 0.5s ease-out;
            transition: opacity 0.3s ease, transform 0.3s ease;
        }
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        /* 卡片样式 */
        .card {
            border: none;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.07);
            border-radius: 12px;
            transition: all 0.3s ease;
        }
        .card:hover {
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }
        .card-header {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            border-bottom: 1px solid #dee2e6;
            border-radius: 12px 12px 0 0 !important;
        }
        
        /* 配置项样式 */
        .config-item {
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            background: linear-gradient(135deg, #ffffff, #f8f9fa);
            transition: all 0.3s ease;
            animation: slideInLeft 0.4s ease-out;
        }
        .config-item:hover {
            border-color: #007bff;
            box-shadow: 0 2px 8px rgba(0, 123, 255, 0.1);
            transform: translateX(5px);
        }
        @keyframes slideInLeft {
            from {
                opacity: 0;
                transform: translateX(-20px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }
        
        /* 表单控件样式 */
        .form-control, .form-select {
            border-radius: 6px;
            border: 1px solid #ced4da;
            transition: border-color 0.3s ease, box-shadow 0.3s ease;
        }
        .form-control:focus, .form-select:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
        }
        .form-control:focus {
            transform: scale(1.02);
            transition: all 0.3s ease;
        }
        /* 防止下拉框抖动 */
        .form-select {
            transform: none !important;
        }
        .form-select:focus {
            transform: none !important;
        }
        
        /* 按钮样式 */
        .btn {
            border-radius: 6px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
        }
        .btn-primary {
            background: linear-gradient(135deg, #007bff, #0056b3);
            border: none;
        }
        .btn-success {
            background: linear-gradient(135deg, #28a745, #1e7e34);
            border: none;
        }
        
        /* JSON编辑器样式 */
        .json-editor {
            font-family: 'Courier New', monospace;
            font-size: 0.875rem;
            background: #f8f9fa;
            border-radius: 6px;
        }
        
        /* 预览卡片样式 */
        .preview-card {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            border: 1px solid #dee2e6;
            border-radius: 12px;
            padding: 1.5rem;
            animation: fadeIn 0.5s ease-out;
        }
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        /* 使用说明样式 */
        .usage-guide {
            background: linear-gradient(135deg, #e3f2fd, #f3e5f5);
            border-left: 4px solid #2196f3;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        /* 字段映射样式 */
        .field-mapping-container {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 1rem;
            border: 1px solid #e9ecef;
        }
        
        .mapping-arrow {
            font-size: 1.2rem;
            color: #007bff;
            font-weight: bold;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            height: 38px;
        }
        
        .rule-config-panel {
            background: linear-gradient(135deg, #f8f9fa, #ffffff);
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 0.5rem;
        }
        
        /* 配置区域标题样式 */
        .config-section-title {
            color: #495057;
            font-weight: 600;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #e9ecef;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1.5rem;
            animation: slideInDown 0.5s ease-out;
        }
        @keyframes slideInDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        .usage-guide h6 {
            color: #1976d2;
            margin-bottom: 0.5rem;
        }
        .usage-guide ul {
            margin-bottom: 0;
            padding-left: 1.2rem;
        }
        .usage-guide li {
            margin-bottom: 0.3rem;
            color: #424242;
        }
        
        /* 进度条动画 */
        .progress-bar {
            background: linear-gradient(90deg, #007bff, #0056b3);
            transition: width 0.6s ease;
        }
        
        /* 图标动画 */
        .bi {
            transition: transform 0.3s ease;
        }
        .btn:hover .bi {
            transform: scale(1.1);
        }
    </style>
</head>
<body>
    <div class="container-fluid py-4">
        <!-- 使用说明 -->
        <div class="usage-guide">
            <h6><i class="bi bi-info-circle"></i> 模板创建使用指南</h6>
            <ul>
                <li><strong>步骤1 - 基本信息：</strong>填写模板名称、描述和选择模板类型（表格式/单据式/混合模板）</li>
                <li><strong>步骤2 - 数据源配置：</strong>设置输入文件格式、读取方向、数据区域等参数</li>
                <li><strong>步骤3 - 处理规则：</strong>配置字段映射、数据转换、验证规则等处理逻辑</li>
                <li><strong>步骤4 - 输出配置：</strong>定义输出文件格式、字段结构和文件名模板</li>
                <li><strong>步骤5 - 预览确认：</strong>查看完整配置并保存模板</li>
            </ul>
        </div>
        
        <!-- 页面标题 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h1 class="h3 mb-1">创建新模板</h1>
                        <p class="text-muted mb-0">配置数据处理模板的各项参数</p>
                    </div>
                    <div>
                        <a href="{% url 'template_management:template_list' %}" class="btn btn-outline-secondary">
                            <i class="bi bi-arrow-left me-2"></i>返回列表
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- 步骤指示器 -->
        <div class="step-indicator">
            <div class="step active" id="step1">
                <div class="step-circle">1</div>
                <div class="step-label">基本信息</div>
            </div>
            <div class="step" id="step2">
                <div class="step-circle">2</div>
                <div class="step-label">数据源配置</div>
            </div>
            <div class="step" id="step3">
                <div class="step-circle">3</div>
                <div class="step-label">处理规则</div>
            </div>
            <div class="step" id="step4">
                <div class="step-circle">4</div>
                <div class="step-label">输出配置</div>
            </div>
            <div class="step" id="step5">
                <div class="step-circle">5</div>
                <div class="step-label">预览确认</div>
            </div>
        </div>
        
        <!-- 进度条 -->
        <div class="progress mb-4" style="height: 6px;">
            <div class="progress-bar" role="progressbar" style="width: 20%" id="progressBar"></div>
        </div>

        <form id="templateForm">
            {% csrf_token %}
            
            <!-- 步骤1: 基本信息 -->
            <div class="step-content" id="step1-content">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-info-circle me-2"></i>基本信息</h5>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info mb-3">
                            <i class="bi bi-lightbulb me-2"></i>
                            <strong>使用说明：</strong>请填写模板的基本信息，包括名称、类型和描述。模板名称应该简洁明了，便于识别和管理。
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="templateName" class="form-label">模板名称 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="templateName" name="name" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="templateType" class="form-label">模板类型 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="templateType" name="template_type" required>
                                        <option value="tabular">表格式模板</option>
                                        <option value="document">单据式模板</option>
                                        <option value="mixed">混合模板</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="dataSourceType" class="form-label">数据源类型 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="dataSourceType" name="data_source_type" required>
                                        <option value="single_file">单文件处理</option>
                                        <option value="multi_file">多文件关联</option>
                                        <option value="one_to_many">一对多生成</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="templateDescription" class="form-label">模板描述</label>
                            <textarea class="form-control" id="templateDescription" name="description" rows="3" placeholder="请描述此模板的用途和功能"></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 步骤2: 数据源配置 -->
            <div class="step-content d-none" id="step2-content">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="bi bi-database me-2"></i>数据源配置</h5>
                        <button type="button" class="btn btn-sm btn-primary" onclick="addDataSource()">
                            <i class="bi bi-plus-circle me-1"></i>添加数据源
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info mb-3">
                            <i class="bi bi-lightbulb me-2"></i>
                            <strong>使用说明：</strong>配置数据源信息，包括文件类型、读取方向和数据区域。
                        </div>
                        <div id="dataSourcesContainer">
                            <!-- 数据源配置项将在这里动态添加 -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- 步骤3: 处理规则 -->
            <div class="step-content d-none" id="step3-content">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="bi bi-gear me-2"></i>处理规则</h5>
                        <button type="button" class="btn btn-sm btn-primary" onclick="addProcessingRule()">
                            <i class="bi bi-plus-circle me-1"></i>添加规则
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info mb-3">
                            <i class="bi bi-lightbulb me-2"></i>
                            <strong>使用说明：</strong>定义数据处理规则，包括字段映射、数据转换、验证等。规则按执行顺序排列。可以不添加处理规则，直接进行数据输出。
                        </div>
                        <div id="processingRulesContainer">
                            <!-- 处理规则配置项将在这里动态添加 -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- 步骤4: 输出配置 -->
            <div class="step-content d-none" id="step4-content">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="bi bi-file-earmark-arrow-down me-2"></i>输出配置</h5>
                        <button type="button" class="btn btn-sm btn-primary" onclick="addOutputConfig()">
                            <i class="bi bi-plus-circle me-1"></i>添加输出
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info mb-3">
                            <i class="bi bi-lightbulb me-2"></i>
                            <strong>使用说明：</strong>配置输出文件的格式、类型和文件名模板。文件名模板支持变量，如{date}表示当前日期。至少需要配置一个输出。
                        </div>
                        <div id="outputConfigsContainer">
                            <!-- 输出配置项将在这里动态添加 -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- 步骤5: 预览确认 -->
            <div class="step-content d-none" id="step5-content">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-eye me-2"></i>预览确认</h5>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-success mb-3">
                            <i class="bi bi-check-circle me-2"></i>
                            <strong>最后确认：</strong>请仔细检查以下配置信息，确认无误后点击"创建模板"按钮完成模板创建。
                        </div>
                        <div id="templatePreview" class="preview-card">
                            <!-- 模板预览内容将在这里显示 -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- 导航按钮 -->
            <div class="d-flex justify-content-between mt-4">
                <button type="button" class="btn btn-outline-secondary" id="prevBtn" onclick="changeStep(-1)" disabled>
                    <i class="bi bi-arrow-left me-2"></i>上一步
                </button>
                <button type="button" class="btn btn-primary" id="nextBtn" onclick="changeStep(1)">
                    下一步<i class="bi bi-arrow-right ms-2"></i>
                </button>
                <button type="submit" class="btn btn-success d-none" id="submitBtn">
                    <i class="bi bi-check-circle me-2"></i>创建模板
                </button>
            </div>
        </form>
    </div>

    <!-- Toast 通知容器 -->
    <div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 11000;">
        <!-- Toast 消息将动态插入到这里 -->
    </div>
    
    <script src="{% static 'js/bootstrap.bundle.min.js' %}"></script>
    <!-- 引入全局通知函数 -->
    {% load static %}
    <script src="{% static 'js/main.js' %}"></script>
    <script>
        let currentStep = 1;
        const totalSteps = 5;
        let dataSourceCounter = 0;
        let processingRuleCounter = 0;
        let outputConfigCounter = 0;

        function changeStep(direction) {
            const newStep = currentStep + direction;
            
            if (newStep < 1 || newStep > totalSteps) {
                return;
            }

            // 验证当前步骤
            if (direction > 0 && !validateCurrentStep()) {
                return;
            }

            // 添加淡出动画
            const currentContent = document.getElementById(`step${currentStep}-content`);
            currentContent.style.opacity = '0';
            currentContent.style.transform = 'translateY(-20px)';
            
            setTimeout(() => {
                // 隐藏当前步骤
                currentContent.classList.add('d-none');
                currentContent.style.opacity = '1';
                currentContent.style.transform = 'translateY(0)';
                document.getElementById(`step${currentStep}`).classList.remove('active');
                if (direction > 0) {
                    document.getElementById(`step${currentStep}`).classList.add('completed');
                }

                // 显示新步骤
                currentStep = newStep;
                const newContent = document.getElementById(`step${currentStep}-content`);
                newContent.classList.remove('d-none');
                newContent.style.opacity = '0';
                newContent.style.transform = 'translateY(20px)';
                
                // 更新步骤指示器
                document.getElementById(`step${currentStep}`).classList.add('active');
                if (direction < 0) {
                    document.getElementById(`step${currentStep}`).classList.remove('completed');
                }
                
                // 添加淡入动画
                setTimeout(() => {
                    newContent.style.opacity = '1';
                    newContent.style.transform = 'translateY(0)';
                }, 50);
                
                // 更新按钮状态
                updateButtons();
                
                // 更新进度条
                updateProgressBar();

                // 如果是最后一步，生成预览
                if (currentStep === totalSteps) {
                    generatePreview();
                }
            }, 200);
        }
        
        function updateProgressBar() {
            const progress = (currentStep / totalSteps) * 100;
            document.getElementById('progressBar').style.width = progress + '%';
        }

        function updateButtons() {
            const prevBtn = document.getElementById('prevBtn');
            const nextBtn = document.getElementById('nextBtn');
            const submitBtn = document.getElementById('submitBtn');

            prevBtn.disabled = currentStep === 1;
            
            if (currentStep === totalSteps) {
                nextBtn.classList.add('d-none');
                submitBtn.classList.remove('d-none');
            } else {
                nextBtn.classList.remove('d-none');
                submitBtn.classList.add('d-none');
            }
        }

        function validateCurrentStep() {
            switch (currentStep) {
                case 1:
                    const name = document.getElementById('templateName').value.trim();
                    if (!name) {
                        showError('请输入模板名称');
                        return false;
                    }
                    return true;
                case 2:
                    const dataSources = document.querySelectorAll('.data-source-item');
                    if (dataSources.length === 0) {
                        showError('请至少添加一个数据源');
                        return false;
                    }
                    
                    // 验证每个数据源的名称不能为空
                    for (let i = 0; i < dataSources.length; i++) {
                        const dataSource = dataSources[i];
                        const nameInput = dataSource.querySelector('input[name^="ds_name_"]');
                        if (nameInput && !nameInput.value.trim()) {
                            showError('数据源名称不能为空');
                            nameInput.focus();
                            return false;
                        }
                    }
                    return true;
                case 3:
                    const processingRules = document.querySelectorAll('.processing-rule-item');
                    
                    // 验证每个处理规则的名称不能为空
                    for (let i = 0; i < processingRules.length; i++) {
                        const rule = processingRules[i];
                        const nameInput = rule.querySelector('input[name^="rule_name_"]');
                        if (nameInput && !nameInput.value.trim()) {
                            showError('规则名称不能为空');
                            nameInput.focus();
                            return false;
                        }
                    }
                    return true;
                case 4:
                    const outputs = document.querySelectorAll('.output-config-item');
                    if (outputs.length === 0) {
                        showError('请至少添加一个输出配置');
                        return false;
                    }
                    return true;
                default:
                    return true;
            }
        }

        function addDataSource() {
            dataSourceCounter++;
            const container = document.getElementById('dataSourcesContainer');
            const html = `
                <div class="config-item data-source-item" id="dataSource${dataSourceCounter}" style="opacity: 0; transform: translateX(-20px);">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6 class="mb-0"><i class="bi bi-database me-2"></i>数据源 ${dataSourceCounter}</h6>
                        <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeDataSource(${dataSourceCounter})">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label"><i class="bi bi-file-earmark me-1"></i>数据源名称<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="ds_name_${dataSourceCounter}" placeholder="如：主数据文件" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label"><i class="bi bi-file-earmark me-1"></i>数据源类型</label>
                                <select class="form-select" name="ds_type_${dataSourceCounter}">
                                    <option value="excel">Excel文件 (.xlsx/.xls)</option>
                                    <option value="csv">CSV文件 (.csv)</option>
                                    <option value="json">JSON文件 (.json)</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label"><i class="bi bi-arrow-right me-1"></i>读取方向</label>
                                <select class="form-select" name="ds_direction_${dataSourceCounter}">
                                    <option value="horizontal">水平读取 (按行)</option>
                                    <option value="vertical">垂直读取 (按列)</option>
                                    <option value="cross">交叉读取</option>
                                    <option value="custom">自定义读取</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><i class="bi bi-table me-1"></i>数据区域配置</label>
                        <div class="row">
                            <div class="col-md-4">
                                <label class="form-label">起始行</label>
                                <input type="number" class="form-control" name="ds_start_row_${dataSourceCounter}" value="1" min="1" placeholder="1">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">结束行</label>
                                <input type="number" class="form-control" name="ds_end_row_${dataSourceCounter}" value="-1" placeholder="-1 (最后一行)">
                                <small class="form-text text-muted">-1表示最后一行</small>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">列范围</label>
                                <input type="text" class="form-control" name="ds_columns_${dataSourceCounter}" placeholder="A,B,C 或 A:F">
                                <small class="form-text text-muted">用逗号分隔或用冒号表示范围</small>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', html);
            
            // 添加动画效果
            const newItem = container.lastElementChild;
            setTimeout(() => {
                newItem.style.opacity = '1';
                newItem.style.transform = 'translateX(0)';
            }, 50);
        }

        function removeDataSource(id) {
            const element = document.getElementById(`dataSource${id}`);
            if (element) {
                // 添加删除动画
                element.style.opacity = '0';
                element.style.transform = 'translateX(-20px)';
                element.style.maxHeight = element.offsetHeight + 'px';
                
                setTimeout(() => {
                    element.style.maxHeight = '0';
                    element.style.marginBottom = '0';
                    element.style.paddingTop = '0';
                    element.style.paddingBottom = '0';
                    
                    setTimeout(() => {
                        element.remove();
                    }, 300);
                }, 200);
            }
        }

        function addProcessingRule() {
            processingRuleCounter++;
            const container = document.getElementById('processingRulesContainer');
            const html = `
                <div class="config-item processing-rule-item" id="processingRule${processingRuleCounter}" style="opacity: 0; transform: translateX(-20px);">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6 class="mb-0"><i class="bi bi-gear me-2"></i>处理规则 ${processingRuleCounter}</h6>
                        <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeProcessingRule(${processingRuleCounter})">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label"><i class="bi bi-tag me-1"></i>规则名称<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="rule_name_${processingRuleCounter}" placeholder="如：字段映射" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label"><i class="bi bi-list-ul me-1"></i>规则类型</label>
                                <select class="form-select" name="rule_type_${processingRuleCounter}" onchange="updateRuleConfigPanel(${processingRuleCounter})">
                                    <option value="data_extraction">数据提取</option>
                                    <option value="field_mapping">字段映射</option>
                                    <option value="data_transformation">数据转换</option>
                                    <option value="data_validation">数据验证</option>
                                    <option value="data_aggregation">数据聚合</option>
                                    <option value="file_association">文件关联</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label"><i class="bi bi-sort-numeric-up me-1"></i>执行顺序</label>
                                <input type="number" class="form-control" name="rule_order_${processingRuleCounter}" value="${processingRuleCounter}" min="1">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><i class="bi bi-gear me-1"></i>规则配置</label>
                        <div class="rule-config-panel" id="ruleConfig${processingRuleCounter}"></div>
                    </div>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', html);
            
            // 初始化该规则的配置面板
            updateRuleConfigPanel(processingRuleCounter);
            
            // 添加动画效果
            const newItem = container.lastElementChild;
            setTimeout(() => {
                newItem.style.opacity = '1';
                newItem.style.transform = 'translateX(0)';
            }, 50);
        }

        function removeProcessingRule(id) {
            const element = document.getElementById(`processingRule${id}`);
            if (element) {
                // 添加删除动画
                element.style.opacity = '0';
                element.style.transform = 'translateX(-20px)';
                element.style.maxHeight = element.offsetHeight + 'px';
                
                setTimeout(() => {
                    element.style.maxHeight = '0';
                    element.style.marginBottom = '0';
                    element.style.paddingTop = '0';
                    element.style.paddingBottom = '0';
                    
                    setTimeout(() => {
                        element.remove();
                    }, 300);
                }, 200);
            }
        }

        function addOutputConfig() {
            outputConfigCounter++;
            const container = document.getElementById('outputConfigsContainer');
            const html = `
                <div class="config-item output-config-item" id="outputConfig${outputConfigCounter}" style="opacity: 0; transform: translateX(-20px);">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6 class="mb-0"><i class="bi bi-file-earmark-arrow-down me-2"></i>输出配置 ${outputConfigCounter}</h6>
                        <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeOutputConfig(${outputConfigCounter})">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                    <div class="row">
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label class="form-label"><i class="bi bi-tag me-1"></i>输出名称</label>
                                <input type="text" class="form-control" name="output_name_${outputConfigCounter}" placeholder="如：处理结果" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label class="form-label"><i class="bi bi-list-ul me-1"></i>输出类型</label>
                                <select class="form-select" name="output_type_${outputConfigCounter}">
                                    <option value="single_file">单文件输出</option>
                                    <option value="multiple_files">多文件输出</option>
                                    <option value="single_row">单行输出</option>
                                    <option value="multiple_rows">多行输出</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label class="form-label"><i class="bi bi-file-earmark me-1"></i>输出格式</label>
                                <select class="form-select" name="output_format_${outputConfigCounter}">
                                    <option value="excel">Excel格式 (.xlsx)</option>
                                    <option value="csv">CSV格式 (.csv)</option>
                                    <option value="json">JSON格式 (.json)</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label class="form-label"><i class="bi bi-file-text me-1"></i>文件名模板</label>
                                <input type="text" class="form-control" name="output_filename_${outputConfigCounter}" placeholder="如：result_{date}.xlsx">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><i class="bi bi-file-earmark-text me-1"></i>输出配置</label>
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">数据源名称</label>
                                <input type="text" class="form-control" name="output_source_name_${outputConfigCounter}" placeholder="处理结果">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">工作表名称</label>
                                <input type="text" class="form-control" name="output_sheet_name_${outputConfigCounter}" placeholder="Sheet1">
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-md-4">
                                <label class="form-label">包含表头</label>
                                <select class="form-select" name="output_include_header_${outputConfigCounter}">
                                    <option value="true">是</option>
                                    <option value="false">否</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">起始行</label>
                                <input type="number" class="form-control" name="output_start_row_${outputConfigCounter}" value="1" min="1">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">起始列</label>
                                <input type="text" class="form-control" name="output_start_col_${outputConfigCounter}" value="A" placeholder="A">
                            </div>
                        </div>
                    </div>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', html);
            
            // 添加动画效果
            const newItem = container.lastElementChild;
            setTimeout(() => {
                newItem.style.opacity = '1';
                newItem.style.transform = 'translateX(0)';
            }, 50);
        }

        function removeOutputConfig(id) {
            const element = document.getElementById(`outputConfig${id}`);
            if (element) {
                // 添加删除动画
                element.style.opacity = '0';
                element.style.transform = 'translateX(-20px)';
                element.style.maxHeight = element.offsetHeight + 'px';
                
                setTimeout(() => {
                    element.style.maxHeight = '0';
                    element.style.marginBottom = '0';
                    element.style.paddingTop = '0';
                    element.style.paddingBottom = '0';
                    
                    setTimeout(() => {
                        element.remove();
                    }, 300);
                }, 200);
            }
        }

        // 添加字段映射
        function addFieldMapping(ruleId) {
            const container = document.getElementById(`fieldMapping${ruleId}`);
            const mappingCount = container.children.length + 1;
            const html = `
                <div class="row mb-2">
                    <div class="col-md-5">
                        <input type="text" class="form-control" name="rule_source_field_${ruleId}_${mappingCount}" placeholder="源字段">
                    </div>
                    <div class="col-md-2 text-center">
                        <span class="mapping-arrow">→</span>
                    </div>
                    <div class="col-md-5">
                        <input type="text" class="form-control" name="rule_target_field_${ruleId}_${mappingCount}" placeholder="目标字段">
                    </div>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', html);
        }

        // 解析列范围字符串
        function parseColumns(columnsStr) {
            if (!columnsStr) return [];
            
            if (columnsStr.includes(':')) {
                // 处理范围格式 A:F
                const [start, end] = columnsStr.split(':');
                const columns = [];
                const startCode = start.charCodeAt(0);
                const endCode = end.charCodeAt(0);
                for (let i = startCode; i <= endCode; i++) {
                    columns.push(String.fromCharCode(i));
                }
                return columns;
            } else {
                // 处理逗号分隔格式 A,B,C
                return columnsStr.split(',').map(col => col.trim());
            }
        }

        function generatePreview() {
            const preview = document.getElementById('templatePreview');
            const formData = new FormData(document.getElementById('templateForm'));
            
            let previewHtml = `
                <h6>基本信息</h6>
                <ul>
                    <li><strong>模板名称:</strong> ${formData.get('name')}</li>
                    <li><strong>模板类型:</strong> ${document.getElementById('templateType').selectedOptions[0].text}</li>
                    <li><strong>数据源类型:</strong> ${document.getElementById('dataSourceType').selectedOptions[0].text}</li>
                    <li><strong>描述:</strong> ${formData.get('description') || '无'}</li>
                </ul>
                
                <h6>数据源配置</h6>
                <ul>
            `;
            
            const dataSources = document.querySelectorAll('.data-source-item');
            dataSources.forEach((ds, index) => {
                const name = ds.querySelector(`input[name^="ds_name_"]`).value;
                const type = ds.querySelector(`select[name^="ds_type_"]`).selectedOptions[0].text;
                previewHtml += `<li>${name} (${type})</li>`;
            });
            
            previewHtml += `</ul><h6>处理规则</h6><ul>`;
            
            const rules = document.querySelectorAll('.processing-rule-item');
            rules.forEach((rule, index) => {
                const name = rule.querySelector(`input[name^="rule_name_"]`).value;
                const type = rule.querySelector(`select[name^="rule_type_"]`).selectedOptions[0].text;
                previewHtml += `<li>${name} (${type})</li>`;
            });
            
            previewHtml += `</ul><h6>输出配置</h6><ul>`;
            
            const outputs = document.querySelectorAll('.output-config-item');
            outputs.forEach((output, index) => {
                const name = output.querySelector(`input[name^="output_name_"]`).value;
                const type = output.querySelector(`select[name^="output_type_"]`).selectedOptions[0].text;
                previewHtml += `<li>${name} (${type})</li>`;
            });
            
            previewHtml += `</ul>`;
            
            preview.innerHTML = previewHtml;
        }

        // 表单提交
        document.getElementById('templateForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            
            // 收集数据源配置
            const dataSourcesConfig = [];
            document.querySelectorAll('.data-source-item').forEach((item, index) => {
                const id = item.id.replace('dataSource', '');
                const config = {
                    source_name: formData.get(`ds_name_${id}`),
                    source_type: formData.get(`ds_type_${id}`),
                    read_direction: formData.get(`ds_direction_${id}`),
                    source_order: index,
                    data_range: {},
                    header_config: {has_header: true},
                    join_keys: [],
                    filter_conditions: []
                };
                
                // 构建数据区域配置
                const startRow = parseInt(formData.get(`ds_start_row_${id}`)) || 1;
                const endRow = parseInt(formData.get(`ds_end_row_${id}`)) || -1;
                const columnsStr = formData.get(`ds_columns_${id}`);
                const columns = parseColumns(columnsStr);
                
                config.data_range = {
                    start_row: startRow,
                    end_row: endRow,
                    columns: columns
                };
                
                dataSourcesConfig.push(config);
            });
            
            // 收集处理规则配置
            const processingRulesConfig = [];
            document.querySelectorAll('.processing-rule-item').forEach((item, index) => {
                const id = item.id.replace('processingRule', '');
                const config = {
                    rule_name: formData.get(`rule_name_${id}`),
                    rule_type: formData.get(`rule_type_${id}`),
                    rule_order: parseInt(formData.get(`rule_order_${id}`)) || index,
                    rule_config: {},
                    condition_config: {}
                };
                
                // 按规则类型收集配置
                if (config.rule_type === 'field_mapping') {
                    const sourceName = formData.get(`rule_source_name_${id}`);
                    const targetField = formData.get(`rule_target_field_${id}`);
                    const mappingRules = {};
                    const mappingContainer = document.getElementById(`fieldMapping${id}`);
                    if (mappingContainer) {
                        mappingContainer.querySelectorAll('.row').forEach((row, mappingIndex) => {
                            const sourceField = formData.get(`rule_source_field_${id}_${mappingIndex + 1}`);
                            const targetFieldMapping = formData.get(`rule_target_field_${id}_${mappingIndex + 1}`);
                            if (sourceField && targetFieldMapping) {
                                mappingRules[targetFieldMapping] = sourceField;
                            }
                        });
                    }
                    config.rule_config = {
                        source_name: sourceName || '主数据文件',
                        target_field: targetField,
                        mapping_rules: mappingRules
                    };
                } else {
                    // 通用：解析JSON文本域
                    let raw = formData.get(`rule_config_json_${id}`) || '{}';
                    try {
                        config.rule_config = raw ? JSON.parse(raw) : {};
                    } catch (err) {
                        config.rule_config = { raw_config: raw };
                    }
                }
                
                processingRulesConfig.push(config);
            });
            
            // 收集输出配置
            const outputConfigsConfig = [];
            document.querySelectorAll('.output-config-item').forEach((item, index) => {
                const id = item.id.replace('outputConfig', '');
                const config = {
                    output_name: formData.get(`output_name_${id}`),
                    output_type: formData.get(`output_type_${id}`),
                    output_format: formData.get(`output_format_${id}`),
                    filename_template: formData.get(`output_filename_${id}`),
                    output_config: {}
                };
                
                // 构建输出配置
                const sourceName = formData.get(`output_source_name_${id}`);
                const sheetName = formData.get(`output_sheet_name_${id}`);
                const includeHeader = formData.get(`output_include_header_${id}`) === 'true';
                const startRow = parseInt(formData.get(`output_start_row_${id}`)) || 1;
                const startCol = formData.get(`output_start_col_${id}`) || 'A';
                
                config.output_config = {
                    source_name: sourceName || '处理结果',
                    sheet_name: sheetName || 'Sheet1',
                    include_header: includeHeader,
                    start_row: startRow,
                    start_col: startCol
                };
                
                outputConfigsConfig.push(config);
            });
            
            // 构建提交数据
            const submitData = new FormData();
            submitData.append('name', formData.get('name'));
            submitData.append('description', formData.get('description'));
            submitData.append('file_type', formData.get('data_source_type') || 'excel');
            submitData.append('output_format', formData.get('template_type') || 'excel');
            
            // 直接提交三大块配置，后端分别解析
            submitData.append('data_sources', JSON.stringify(dataSourcesConfig));
            submitData.append('processing_rules', JSON.stringify(processingRulesConfig));
            submitData.append('output_configs', JSON.stringify(outputConfigsConfig));
            submitData.append('csrfmiddlewaretoken', formData.get('csrfmiddlewaretoken'));
            
            // console.log(submitData);
            // 提交表单（修正URL：使用连字符路径）
            fetch('/template-management/templates/create/', {
                method: 'POST',
                body: submitData
            })
            .then(async response => {
                const contentType = response.headers.get('content-type') || '';
                if (!contentType.includes('application/json')) {
                    const text = await response.text();
                    throw new Error(`服务器返回非JSON响应: ${response.status} ${text.slice(0, 200)}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showSuccess('模板创建成功！');
                    setTimeout(() => {
                        window.location.href = '/template-management/';
                    }, 1500);
                } else {
                    showError('创建失败: ' + (data.error || '未知错误'));
                }
            })
            .catch(error => {
                showError('创建失败: ' + error.message);
            });
        });

        // 初始化：添加默认的数据源和输出配置
        document.addEventListener('DOMContentLoaded', function() {
            addDataSource();
            addOutputConfig();
        });

        // 添加数据转换规则
        function addTransformationRule(ruleId) {
            const container = document.getElementById(`transformationRules${ruleId}`);
            const ruleCount = container.children.length + 1;
            const html = `
                <div class="card mb-3" id="transformRule${ruleId}_${ruleCount}">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="card-title mb-0">转换规则 ${ruleCount}</h6>
                            <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeTransformationRule('${ruleId}', '${ruleCount}')">
                                <i class="bi bi-trash me-1"></i>删除
                            </button>
                        </div>
                        <div class="row">
                            <div class="col-md-4">
                                <label class="form-label">转换类型</label>
                                <select class="form-select" name="transform_type_${ruleId}_${ruleCount}" onchange="updateTransformConfig('${ruleId}', '${ruleCount}')">
                                    <option value="">请选择转换类型</option>
                                    <option value="split">字段拆分</option>
                                    <option value="aggregate">字段聚合</option>
                                    <option value="replace">字符替换</option>
                                    <option value="regex_replace">正则替换</option>
                                    <option value="trim">去除空格</option>
                                    <option value="case">大小写转换</option>
                                    <option value="fixed_value">固定值</option>
                                    <option value="format">格式化</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">源字段</label>
                                <input type="text" class="form-control" name="source_field_${ruleId}_${ruleCount}" placeholder="源字段名">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">目标字段</label>
                                <input type="text" class="form-control" name="target_field_${ruleId}_${ruleCount}" placeholder="目标字段名">
                            </div>
                        </div>
                        <div class="mt-3" id="transformConfig${ruleId}_${ruleCount}">
                            <!-- 动态配置区域 -->
                        </div>
                    </div>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', html);
        }

        function removeTransformationRule(ruleId, ruleCount) {
            const element = document.getElementById(`transformRule${ruleId}_${ruleCount}`);
            if (element) {
                element.remove();
            }
        }

        function updateTransformConfig(ruleId, ruleCount) {
            const selectEl = document.querySelector(`select[name="transform_type_${ruleId}_${ruleCount}"]`);
            const configEl = document.getElementById(`transformConfig${ruleId}_${ruleCount}`);
            if (!selectEl || !configEl) return;

            const transformType = selectEl.value;
            let configHtml = '';

            switch (transformType) {
                case 'split':
                    configHtml = `
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">分隔符</label>
                                <input type="text" class="form-control" name="delimiter_${ruleId}_${ruleCount}" placeholder="如：, 或 |">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">拆分方式</label>
                                <select class="form-select" name="split_type_${ruleId}_${ruleCount}">
                                    <option value="expand">拆分为多列</option>
                                    <option value="first">取第一部分</option>
                                    <option value="last">取最后一部分</option>
                                    <option value="nth">取第N部分</option>
                                </select>
                            </div>
                        </div>
                        <div class="row mt-2" id="nthConfig${ruleId}_${ruleCount}" style="display: none;">
                            <div class="col-md-6">
                                <label class="form-label">索引位置 (从0开始)</label>
                                <input type="number" class="form-control" name="nth_${ruleId}_${ruleCount}" min="0">
                            </div>
                        </div>
                    `;
                    break;
                case 'aggregate':
                    configHtml = `
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">聚合方式</label>
                                <select class="form-select" name="agg_method_${ruleId}_${ruleCount}">
                                    <option value="concat">字符串连接</option>
                                    <option value="sum">数值求和</option>
                                    <option value="mean">数值均值</option>
                                    <option value="max">数值最大</option>
                                    <option value="min">数值最小</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">连接符 (字符串连接时)</label>
                                <input type="text" class="form-control" name="separator_${ruleId}_${ruleCount}" placeholder="如：, ">
                            </div>
                        </div>
                        <div class="mt-2">
                            <label class="form-label">源字段列表 (逗号分隔)</label>
                            <input type="text" class="form-control" name="source_fields_${ruleId}_${ruleCount}" placeholder="字段1,字段2,字段3">
                        </div>
                    `;
                    break;
                case 'replace':
                    configHtml = `
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">原字符串</label>
                                <input type="text" class="form-control" name="old_value_${ruleId}_${ruleCount}" placeholder="要被替换的字符串">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">新字符串</label>
                                <input type="text" class="form-control" name="new_value_${ruleId}_${ruleCount}" placeholder="替换后的字符串">
                            </div>
                        </div>
                    `;
                    break;
                case 'regex_replace':
                    configHtml = `
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">正则表达式</label>
                                <input type="text" class="form-control" name="regex_pattern_${ruleId}_${ruleCount}" placeholder="如：\\d{3}-\\d{4}">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">替换内容</label>
                                <input type="text" class="form-control" name="regex_replacement_${ruleId}_${ruleCount}" placeholder="替换后的内容">
                            </div>
                        </div>
                    `;
                    break;
                case 'trim':
                    configHtml = `
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">去除类型</label>
                                <select class="form-select" name="trim_type_${ruleId}_${ruleCount}">
                                    <option value="both">两端空格</option>
                                    <option value="left">左端空格</option>
                                    <option value="right">右端空格</option>
                                    <option value="all">所有空格</option>
                                </select>
                            </div>
                        </div>
                    `;
                    break;
                case 'case':
                    configHtml = `
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">转换类型</label>
                                <select class="form-select" name="case_type_${ruleId}_${ruleCount}">
                                    <option value="upper">转为大写</option>
                                    <option value="lower">转为小写</option>
                                    <option value="title">首字母大写</option>
                                    <option value="capitalize">句首大写</option>
                                </select>
                            </div>
                        </div>
                    `;
                    break;
                case 'fixed_value':
                    configHtml = `
                        <div class="row">
                            <div class="col-md-12">
                                <label class="form-label">固定值</label>
                                <input type="text" class="form-control" name="fixed_value_${ruleId}_${ruleCount}" placeholder="设置固定值">
                            </div>
                        </div>
                    `;
                    break;
                case 'format':
                    configHtml = `
                        <div class="row">
                            <div class="col-md-12">
                                <label class="form-label">格式模板</label>
                                <input type="text" class="form-control" name="format_template_${ruleId}_${ruleCount}" placeholder="如：{value}_suffix 或 prefix_{value}">
                                <small class="form-text text-muted">使用 {value} 表示原字段值</small>
                            </div>
                        </div>
                    `;
                    break;
            }

            configEl.innerHTML = configHtml;

            // 为拆分方式添加动态显示
            if (transformType === 'split') {
                const splitTypeEl = document.querySelector(`select[name="split_type_${ruleId}_${ruleCount}"]`);
                if (splitTypeEl) {
                    splitTypeEl.addEventListener('change', function() {
                        const nthConfigEl = document.getElementById(`nthConfig${ruleId}_${ruleCount}`);
                        if (nthConfigEl) {
                            nthConfigEl.style.display = this.value === 'nth' ? 'block' : 'none';
                        }
                    });
                }
            }
        }

        // 动态更新规则配置面板，根据规则类型渲染不同UI
        function updateRuleConfigPanel(ruleId) {
            const selectEl = document.querySelector(`select[name="rule_type_${ruleId}"]`);
            const panelEl = document.getElementById(`ruleConfig${ruleId}`);
            if (!selectEl || !panelEl) return;

            const ruleType = selectEl.value;

            if (ruleType === 'field_mapping') {
                panelEl.innerHTML = `
                    <div class="mb-3">
                        <label class="form-label"><i class="bi bi-file-earmark me-1"></i>数据源名称</label>
                        <input type="text" class="form-control" name="rule_source_name_${ruleId}" placeholder="如：主数据文件">
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <label class="form-label mb-0"><i class="bi bi-diagram-3 me-1"></i>字段映射</label>
                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="addFieldMapping(${ruleId})">
                            <i class="bi bi-plus-circle me-1"></i>添加映射
                        </button>
                    </div>
                    <div id="fieldMapping${ruleId}"></div>
                `;
                // 默认添加一行映射，便于上手
                setTimeout(() => addFieldMapping(ruleId), 0);
            } else if (ruleType === 'data_transformation') {
                panelEl.innerHTML = `
                    <div class="mb-3">
                        <label class="form-label"><i class="bi bi-file-earmark me-1"></i>数据源名称</label>
                        <input type="text" class="form-control" name="rule_source_name_${ruleId}" placeholder="如：主数据文件">
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <label class="form-label mb-0"><i class="bi bi-arrow-left-right me-1"></i>转换规则</label>
                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="addTransformationRule(${ruleId})">
                            <i class="bi bi-plus-circle me-1"></i>添加转换
                        </button>
                    </div>
                    <div id="transformationRules${ruleId}"></div>
                `;
                // 默认添加一个转换规则
                setTimeout(() => addTransformationRule(ruleId), 0);
            } else {
                // 其他规则统一使用JSON文本编辑区域，避免出现不相关字段
                panelEl.innerHTML = `
                    <div class="mb-3">
                        <label class="form-label"><i class="bi bi-braces me-1"></i>规则配置 (JSON)</label>
                        <textarea class="form-control json-editor" name="rule_config_json_${ruleId}" rows="6" placeholder='{"example": "value"}'></textarea>
                        <div class="form-text">请输入与所选规则类型匹配的JSON配置；如无需特殊配置可留空。</div>
                    </div>
                `;
            }
        }
    </script>
</body>
</html>


